use iced::{Element, Length, Color};
use iced::widget::{text_input, container, column, row, text, button, scrollable, Space};
use crate::theme::CdbTheme;
use std::collections::HashMap;

/// 数据库对象类型
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum DatabaseObjectType {
    Database,
    Table,
    View,
    Procedure,
    Function,
    Trigger,
    Index,
    Schema,
    Connection,
}

impl DatabaseObjectType {
    /// 获取对象类型的图标
    pub fn icon(&self) -> &'static str {
        match self {
            DatabaseObjectType::Database => "🗄️",
            DatabaseObjectType::Table => "📊",
            DatabaseObjectType::View => "👁️",
            DatabaseObjectType::Procedure => "⚙️",
            DatabaseObjectType::Function => "🔧",
            DatabaseObjectType::Trigger => "⚡",
            DatabaseObjectType::Index => "📇",
            DatabaseObjectType::Schema => "📁",
            DatabaseObjectType::Connection => "🖥️",
        }
    }

    /// 获取对象类型的显示名称
    pub fn display_name(&self) -> &'static str {
        match self {
            DatabaseObjectType::Database => "数据库",
            DatabaseObjectType::Table => "表",
            DatabaseObjectType::View => "视图",
            DatabaseObjectType::Procedure => "存储过程",
            DatabaseObjectType::Function => "函数",
            DatabaseObjectType::Trigger => "触发器",
            DatabaseObjectType::Index => "索引",
            DatabaseObjectType::Schema => "模式",
            DatabaseObjectType::Connection => "连接",
        }
    }
}

/// 数据库对象
#[derive(Debug, Clone, PartialEq)]
pub struct DatabaseObject {
    pub id: String,
    pub name: String,
    pub object_type: DatabaseObjectType,
    pub parent_id: Option<String>,
    pub children: Vec<String>,
    pub is_expanded: bool,
    pub is_favorite: bool,
    pub last_accessed: Option<chrono::DateTime<chrono::Utc>>,
}

impl DatabaseObject {
    pub fn new(id: String, name: String, object_type: DatabaseObjectType) -> Self {
        Self {
            id,
            name,
            object_type,
            parent_id: None,
            children: Vec::new(),
            is_expanded: false,
            is_favorite: false,
            last_accessed: None,
        }
    }

    /// 检查对象是否匹配搜索条件
    pub fn matches_search(&self, query: &str) -> bool {
        if query.is_empty() {
            return true;
        }
        
        let query_lower = query.to_lowercase();
        self.name.to_lowercase().contains(&query_lower)
            || self.object_type.display_name().to_lowercase().contains(&query_lower)
    }

    /// 检查对象是否匹配类型过滤
    pub fn matches_type_filter(&self, filter: &Option<DatabaseObjectType>) -> bool {
        match filter {
            Some(filter_type) => &self.object_type == filter_type,
            None => true,
        }
    }
}

/// 数据库资源管理器组件
#[derive(Debug, Clone)]
pub struct DatabaseExplorer {
    objects: HashMap<String, DatabaseObject>,
    search_query: String,
    type_filter: Option<DatabaseObjectType>,
    show_favorites_only: bool,
    show_recent_only: bool,
    root_objects: Vec<String>,
}

#[derive(Debug, Clone)]
pub enum DatabaseExplorerMessage {
    SearchChanged(String),
    TypeFilterChanged(Option<DatabaseObjectType>),
    ToggleFavoritesOnly,
    ToggleRecentOnly,
    ToggleExpanded(String),
    ToggleFavorite(String),
    SelectObject(String),
    RefreshObjects,
    ClearSearch,
}

impl DatabaseExplorer {
    pub fn new() -> Self {
        let mut explorer = Self {
            objects: HashMap::new(),
            search_query: String::new(),
            type_filter: None,
            show_favorites_only: false,
            show_recent_only: false,
            root_objects: Vec::new(),
        };

        // 添加示例数据
        explorer.add_sample_data();
        explorer
    }

    /// 添加示例数据
    fn add_sample_data(&mut self) {
        // 添加连接
        let conn_id = "localhost".to_string();
        let mut connection = DatabaseObject::new(
            conn_id.clone(),
            "localhost".to_string(),
            DatabaseObjectType::Connection,
        );
        connection.is_expanded = true;

        // 添加数据库
        let db_id = "demo_db".to_string();
        let mut database = DatabaseObject::new(
            db_id.clone(),
            "Demo Database".to_string(),
            DatabaseObjectType::Database,
        );
        database.parent_id = Some(conn_id.clone());
        database.is_expanded = true;

        // 添加表
        let tables = vec![
            ("users", "用户表"),
            ("orders", "订单表"),
            ("products", "产品表"),
            ("categories", "分类表"),
        ];

        for (table_name, description) in tables {
            let table_id = format!("table_{}", table_name);
            let mut table = DatabaseObject::new(
                table_id.clone(),
                format!("{} ({})", table_name, description),
                DatabaseObjectType::Table,
            );
            table.parent_id = Some(db_id.clone());
            database.children.push(table_id.clone());
            self.objects.insert(table_id, table);
        }

        // 添加视图
        let view_id = "user_orders_view".to_string();
        let mut view = DatabaseObject::new(
            view_id.clone(),
            "用户订单视图".to_string(),
            DatabaseObjectType::View,
        );
        view.parent_id = Some(db_id.clone());
        database.children.push(view_id.clone());
        self.objects.insert(view_id, view);

        // 添加存储过程
        let proc_id = "get_user_stats".to_string();
        let mut procedure = DatabaseObject::new(
            proc_id.clone(),
            "获取用户统计".to_string(),
            DatabaseObjectType::Procedure,
        );
        procedure.parent_id = Some(db_id.clone());
        database.children.push(proc_id.clone());
        self.objects.insert(proc_id, procedure);

        connection.children.push(db_id.clone());
        self.objects.insert(db_id, database);
        self.objects.insert(conn_id.clone(), connection);
        self.root_objects.push(conn_id);
    }

    /// 更新搜索查询
    pub fn update_search(&mut self, query: String) {
        self.search_query = query;
    }

    /// 设置类型过滤
    pub fn set_type_filter(&mut self, filter: Option<DatabaseObjectType>) {
        self.type_filter = filter;
    }

    /// 切换收藏夹显示
    pub fn toggle_favorites_only(&mut self) {
        self.show_favorites_only = !self.show_favorites_only;
    }

    /// 切换最近使用显示
    pub fn toggle_recent_only(&mut self) {
        self.show_recent_only = !self.show_recent_only;
    }

    /// 切换对象展开状态
    pub fn toggle_expanded(&mut self, object_id: &str) {
        if let Some(object) = self.objects.get_mut(object_id) {
            object.is_expanded = !object.is_expanded;
        }
    }

    /// 切换收藏状态
    pub fn toggle_favorite(&mut self, object_id: &str) {
        if let Some(object) = self.objects.get_mut(object_id) {
            object.is_favorite = !object.is_favorite;
        }
    }

    /// 获取过滤后的对象列表
    fn get_filtered_objects(&self) -> Vec<&DatabaseObject> {
        self.objects
            .values()
            .filter(|obj| {
                // 搜索过滤
                if !obj.matches_search(&self.search_query) {
                    return false;
                }

                // 类型过滤
                if !obj.matches_type_filter(&self.type_filter) {
                    return false;
                }

                // 收藏夹过滤
                if self.show_favorites_only && !obj.is_favorite {
                    return false;
                }

                // 最近使用过滤
                if self.show_recent_only && obj.last_accessed.is_none() {
                    return false;
                }

                true
            })
            .collect()
    }

    /// 渲染搜索和过滤控件
    fn render_search_controls<'a>(&'a self, theme: &CdbTheme) -> Element<'a, DatabaseExplorerMessage> {
        let search_input = text_input("搜索数据库对象...", &self.search_query)
            .on_input(DatabaseExplorerMessage::SearchChanged)
            .size(12)
            .padding(8);

        let clear_button = button(text("✕").size(12))
            .on_press(DatabaseExplorerMessage::ClearSearch)
            .style(|theme: &iced::Theme, status| {
                button::Style {
                    background: Some(Color::TRANSPARENT.into()),
                    text_color: Color::from_rgb(0.6, 0.6, 0.6),
                    border: iced::Border::default(),
                    shadow: iced::Shadow::default(),
                }
            });

        let search_row = row![
            search_input,
            clear_button
        ]
        .spacing(5)
        .align_y(iced::Alignment::Center);

        // 过滤按钮
        let filter_buttons = row![
            self.create_filter_button("全部", None, theme),
            self.create_filter_button("表", Some(DatabaseObjectType::Table), theme),
            self.create_filter_button("视图", Some(DatabaseObjectType::View), theme),
            self.create_filter_button("存储过程", Some(DatabaseObjectType::Procedure), theme),
        ]
        .spacing(5);

        // 显示选项
        let show_options = row![
            self.create_toggle_button("收藏夹", self.show_favorites_only, DatabaseExplorerMessage::ToggleFavoritesOnly, theme),
            self.create_toggle_button("最近使用", self.show_recent_only, DatabaseExplorerMessage::ToggleRecentOnly, theme),
        ]
        .spacing(5);

        column![
            search_row,
            filter_buttons,
            show_options,
        ]
        .spacing(10)
        .padding(10)
        .into()
    }

    /// 创建过滤按钮
    fn create_filter_button<'a>(
        &self,
        label: &'a str,
        filter_type: Option<DatabaseObjectType>,
        _theme: &CdbTheme,
    ) -> Element<'a, DatabaseExplorerMessage> {
        let is_active = self.type_filter == filter_type;

        button(text(label).size(10))
            .on_press(DatabaseExplorerMessage::TypeFilterChanged(filter_type))
            .style(move |_theme: &iced::Theme, _status| {
                if is_active {
                    button::Style {
                        background: Some(Color::from_rgb(0.2, 0.4, 0.8).into()),
                        text_color: Color::WHITE,
                        border: iced::Border::default(),
                        shadow: iced::Shadow::default(),
                    }
                } else {
                    button::Style {
                        background: Some(Color::from_rgb(0.1, 0.1, 0.1).into()),
                        text_color: Color::from_rgb(0.8, 0.8, 0.8),
                        border: iced::Border::default(),
                        shadow: iced::Shadow::default(),
                    }
                }
            })
            .padding([4, 8])
            .into()
    }

    /// 创建切换按钮
    fn create_toggle_button<'a>(
        &self,
        label: &'a str,
        is_active: bool,
        message: DatabaseExplorerMessage,
        _theme: &CdbTheme,
    ) -> Element<'a, DatabaseExplorerMessage> {
        button(text(label).size(10))
            .on_press(message)
            .style(move |_theme: &iced::Theme, _status| {
                if is_active {
                    button::Style {
                        background: Some(Color::from_rgb(0.2, 0.6, 0.2).into()),
                        text_color: Color::WHITE,
                        border: iced::Border::default(),
                        shadow: iced::Shadow::default(),
                    }
                } else {
                    button::Style {
                        background: Some(Color::from_rgb(0.1, 0.1, 0.1).into()),
                        text_color: Color::from_rgb(0.8, 0.8, 0.8),
                        border: iced::Border::default(),
                        shadow: iced::Shadow::default(),
                    }
                }
            })
            .padding([4, 8])
            .into()
    }

    /// 渲染数据库对象树
    fn render_object_tree<'a>(&'a self, theme: &CdbTheme) -> Element<'a, DatabaseExplorerMessage> {
        let filtered_objects = self.get_filtered_objects();
        let mut tree_items = column![];

        for object_id in &self.root_objects {
            if let Some(object) = self.objects.get(object_id) {
                if filtered_objects.contains(&object) {
                    tree_items = tree_items.push(self.render_object_item(object, 0, theme));
                }
            }
        }

        scrollable(tree_items)
            .width(Length::Fill)
            .height(Length::Fill)
            .into()
    }

    /// 渲染单个对象项
    fn render_object_item<'a>(
        &'a self,
        object: &'a DatabaseObject,
        indent_level: usize,
        theme: &CdbTheme,
    ) -> Element<'a, DatabaseExplorerMessage> {
        let indent = Space::new(Length::Fixed((indent_level * 20) as f32), Length::Fixed(0.0));
        
        let expand_icon = if !object.children.is_empty() {
            if object.is_expanded { "▼" } else { "▶" }
        } else {
            " "
        };

        let favorite_icon = if object.is_favorite { "⭐" } else { " " };

        let item_row = row![
            indent,
            button(text(expand_icon).size(12))
                .on_press(DatabaseExplorerMessage::ToggleExpanded(object.id.clone()))
                .style(|theme: &iced::Theme, status| {
                    button::Style {
                        background: Some(Color::TRANSPARENT.into()),
                        text_color: Color::from_rgb(0.6, 0.6, 0.6),
                        border: iced::Border::default(),
                        shadow: iced::Shadow::default(),
                    }
                }),
            text(object.object_type.icon()).size(14),
            text(&object.name).size(12).color(theme.colors.foreground),
            Space::new(Length::Fill, Length::Fixed(0.0)),
            button(text(favorite_icon).size(12))
                .on_press(DatabaseExplorerMessage::ToggleFavorite(object.id.clone()))
                .style(|theme: &iced::Theme, status| {
                    button::Style {
                        background: Some(Color::TRANSPARENT.into()),
                        text_color: Color::from_rgb(1.0, 0.8, 0.0),
                        border: iced::Border::default(),
                        shadow: iced::Shadow::default(),
                    }
                }),
        ]
        .spacing(5)
        .align_y(iced::Alignment::Center)
        .padding([2, 5]);

        let mut items = column![item_row];

        // 如果展开，显示子对象
        if object.is_expanded {
            for child_id in &object.children {
                if let Some(child) = self.objects.get(child_id) {
                    items = items.push(self.render_object_item(child, indent_level + 1, theme));
                }
            }
        }

        items.into()
    }

    /// 渲染完整的数据库资源管理器
    pub fn view<'a>(&'a self, theme: &CdbTheme) -> Element<'a, DatabaseExplorerMessage> {
        column![
            self.render_search_controls(theme),
            self.render_object_tree(theme),
        ]
        .spacing(5)
        .into()
    }
}

impl Default for DatabaseExplorer {
    fn default() -> Self {
        Self::new()
    }
}
